
<style lang="scss" scoped>
#pay {
  height: auto;
  margin-top: 70px;
  padding: 15px 12px;
}
.order-cart {
  width: 100%;
  height: 106px;
  box-sizing: border-box;
  background: #fff;
  border-radius: 3px;
  padding: 0 12px;
  margin-bottom: 15px;
}

.order-cart > div:first-child {
  width: 100%;
  height: 62px;
  border-bottom: 0.5px solid rgba(238, 238, 238, 1);
}

.order-cart > div > span {
  font-size: 14px;
}

.order-cart > div > font {
  font-size: 14px;
  margin-top: 8px;
}

.order-cart > div > font::before {
  content: "";
  display: inline-block;
  width: 15px;
  height: 15px;
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: top;
  margin-right: 5px;
}

.order-money {
  font-size: 14px;
  font-weight: bolder;
  position: relative;
}

.order-money span {
  position: absolute;
  right: 0px;
  font-weight: normal;
}

.pay-con {
  position: relative;
  background: #fff;
  box-sizing: border-box;
  padding: 15px;
  border-radius: 3px;
}

.amount-wx {
  width: 100%;
  height: 48px;
  border-bottom: 0.5px solid rgba(238, 238, 238, 1);
}
.amount-wx:last-child {
  border-bottom: none;
}

.amount-wx > img:first-child {
  width: 27px;
  height: 23px;
  display: block;
  margin-right: 10px;
}

.amount-wx > span {
  width: 22px;
  height: 22px;
  display: block;
  border-radius: 50%;
  box-sizing: border-box;
  border: 1px solid rgba(198, 198, 198, 1);
}

.amount-wx.active > span {
  border: none;
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
}

.amount-zhi {
  margin-top: 15px;
}

.amount-zhi > img:first-child {
  width: 26px;
  height: 26px;
  display: block;
  margin-right: 10px;
}

.layer {
  width: 100%;
  height: 100%;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  background: #fff;
  position: fixed;
}

.psd-box {
  box-sizing: border-box;
  padding: 0 15px;
  background: rgba(0, 0, 0, 0.5);
}

.psd-box > div {
  background: #fff;
  border-radius: 5px;
  padding: 10px;
  width: 80%;
  margin: 0 auto;
  position: relative;
  text-align: center;
}

.psd-box > div > .close {
  width: 100%;
  height: 30px;
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
  margin-bottom: 10px;
  position: relative;
}

.psd-box > div > .close i {
  position: absolute;
  left: 0px;
  width: 20px;
  height: 20px;
  background: url("/static/ethel_img/shop/icon_close.png") center center
    no-repeat;
  background-size: 100% 100%;
}

.psd-box > div > span {
  font-size: 20px;
  margin-bottom: 10px;
}

.psd-box__warp {
  width: 100%;
  height: 44px;
  box-sizing: border-box;
  border: 1px solid rgba(238, 238, 238, 1);
}

.psd-box__warp li {
  height: 100%;
  text-align: center;
  font-size: 18px;
  line-height: 42px;
  border-right: 1px solid rgba(238, 238, 238, 1);
}

.psd-box__warp li:last-child {
  border-right: none;
}

.keyboard {
  position: relative;
  width: 100%;
}

.keyboard ul li {
  width: 33.3%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-right: 1px solid #e5e5e5;
  border-bottom: 1px solid #e5e5e5;
  text-align: center;
  color: #333;
  font-size: 18px;
  box-sizing: border-box;
}

.border-top {
  border-top: 1px solid #e5e5e5;
}

.keyboard ul li:nth-of-type(3n) {
  border-right: none;
}

.ba-li {
  background: #dbdbdb;
}

.keyboard ul li.border-none {
  border-bottom: none;
}
.btn {
  width: 95%;
  display: block;
  height: 44px;
  line-height: 44px;
  text-align: center;
  color: #fff;
  border: none;
  outline: none;
  margin: 50px auto;
  position: fixed;
  bottom: 0;
  left: 10px;
  right: 10px;
}
.degt {
  display: inline-block;
  width: 10px;
  height: 10px;
  background: #333;
  border-radius: 50%;
}
</style>

<template>
  <div class="withdrawal">
    <ComHeader title="订单支付" leftArrow="true"/>
    <div id="pay">
      <div class="order-cart flex-display flex-display-column">
        <!-- <div class="flex-display flex-display-column flex-center-align flex-center-pack hidden">
                <span>支付剩余时间</span>
                <font>09:23</font>
        </div>-->
        <div class="order-money flex-display flex-num-one flex-center-align">
          {{totalType == 1 ? '订单金额' : '订单积分' }}
          <span
            id="totalId"
            class="theme-color"
          >{{totalType == 1 ? '￥'+ total : total+'积分'}}</span>
        </div>
      </div>
      <div class="pay-con" id="parentBox">
        <div
          v-for="(item, index) in payBtn"
          :key="index"
          :class="{'active':index == payIndex}"
          class="amount-wx flex-display flex-center-align"
          @click="fnSelectPayType(item.type,index)"
        >
          <img :src="item.src">
          <p class="flex-num-one">{{item.name}}</p>
          <span></span>
        </div>
      </div>
      <button class="btn theme-background f-16" @click="paySubmit">确认支付</button>
      <!--支付密码弹窗-->
      <div class="layer flex-display flex-display-column" id="layer" v-if="showLayer">
        <div class="psd-box flex-num-one flex-display flex-center-align">
          <div>
            <div class="close">
              <i tapmode @click="showLayer = false"></i>
              请输入积分支付密码
            </div>
            <span id="yuTotal"></span>
            <ul class="psd-box__warp flex-display" id="passwordBox">
              <li class="flex-num-one"></li>
              <li class="flex-num-one"></li>
              <li class="flex-num-one"></li>
              <li class="flex-num-one"></li>
              <li class="flex-num-one"></li>
              <li class="flex-num-one"></li>
            </ul>
          </div>
        </div>
        <div class="keyboard" id="keyboard">
          <ul class="flex-display flex-warp">
            <li class="border-top" @click="fnHandleSetPassword(1)">1</li>
            <li class="border-top" @click="fnHandleSetPassword(2)">2</li>
            <li class="border-top" @click="fnHandleSetPassword(3)">3</li>
            <li @click="fnHandleSetPassword(4)">4</li>
            <li @click="fnHandleSetPassword(5)">5</li>
            <li @click="fnHandleSetPassword(6)">6</li>
            <li @click="fnHandleSetPassword(7)">7</li>
            <li @click="fnHandleSetPassword(8)">8</li>
            <li @click="fnHandleSetPassword(9)">9</li>
            <li class="ba-li border-none"></li>
            <li class="border-none" @click="fnHandleSetPassword(0)">0</li>
            <li class="ba-li border-none" @click="fnHandleSetPassword('删除')">删除</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import api from "@/fetch/api";
import ComHeader from "@/common/ComHeader";
import Scroll from "@/base/scroll/scroll";
import { Toast, Indicator } from "mint-ui";
export default {
  data() {
    return {
      payType: 1, // 默认微信支付
      total: this.$route.params.total,
      order_code: null, // 订单id列表
      payIndex: 0, // 选择支付方式
      showLayer: false,
      totalType: 0,
      payPsd: "", // 积分支付密码
      paramsObj: null,
      userscore: 0, // 积分余额
      isPayLoading: false, // 是否正在支付控制多重点击
      payBtn: [
        {
          name: "微信支付",
          type: 1,
          src: "static/ethel_img/shop/icon_balance@2x.png"
        },
        {
          name: "积分支付",
          type: 3,
          src: "static/ethel_img/shop/icon_balance@2x.png"
        }
      ]
    };
  },
  created() {
    this.ethelWxUserInfo = this.getlocalStorage(this.companyUnique)
      ? this.getlocalStorage(this.companyUnique)
      : "";
    if (!this.$route.params.total) {
      this.$router.go(-1);
    }
    if (this.$route.params.order_no) {
      this.order_code = this.$route.params.order_no;
    }
    if (this.$route.params) this.initPayBtn();
    this.getUserscore();
  },
  methods: {
    /**
     * @desc 获取积分
     * @param {Number} _num 当前输入得数字
     */
    getUserscore() {
      api.getMyBalance({ uid: this.ethelWxUserInfo.id }).catch(result => {
        if (result.status == 200) {
          this.userscore = result.data.data.userscore;
        }
      });
    },
    /**
     * @desc 输入键盘密码
     * @param {Number} _num 当前输入得数字
     */
    fnHandleSetPassword(_num) {
      let parentBox = document.getElementById("passwordBox");
      let spansBox = parentBox.querySelectorAll("li");
      // 如果当前校验是数字
      if (/[0-9]/.test(_num)) {
        var index = 0;
        for (var i = 0; i < spansBox.length; i++) {
          var val = spansBox[i].innerHTML;
          index = i;
          if (!val) {
            let style =
              "display: inline-block;width:10px;height:10px;background:#333;border-radius: 50%;";
            spansBox[i].innerHTML = "<span></span>";
            spansBox[i].querySelectorAll("span")[0].style = style;
            spansBox[i].setAttribute("data-num", _num);
            break;
          }
        }
        if (index == 5) {
          // 如果索引到第5个 调接口处理逻辑
          var password = "";
          for (var j = 0; j < spansBox.length; j++) {
            var val = spansBox[j].getAttribute("data-num");
            password += val;
          }
          // 调用余额支付
          // 判断当前输入的支付密码是否正确
          console.log(password);
          this.fnCheckPwd(password);
          //fnHandlePswPay(password);
        }
      } else if (_num == "删除") {
        var index = 0;
        for (var i = 0; i < spansBox.length; i++) {
          var val = spansBox[i].innerHTML;
          if (val) {
            index = i;
          }
        }
        spansBox[index].innerHTML = "";
        spansBox[index].setAttribute("data-num", "");
      }
    },

    /**
     * @desc 校验支付密码是否正确
     * @param {Number} pwd 当前输入的密码
     */
    fnCheckPwd(pwd) {
      let params = {
        ope_type: "check",
        is_pay_pw: "yes",
        pay_pw: parseInt(pwd),
        uid: this.ethelWxUserInfo.id
      };
      api
        .userpayinfo(params)
        .catch(res => {
          console.log(res);
          if (res.status === 200) {
            if (res.data.code == 2) {
              Indicator.close();
              Toast({
                message: res.data.msg,
                duration: 2000
              });
            } else {
              Indicator.open({
                text: "支付中...",
                spinnerType: "fading-circle"
              });
              this.payPsd = pwd;
              // 如果存在订单 直接
              this.order_code ? this.integralPay() : this.fnHandleOrder();
            }
          }
        })
        .then(err => {
          Indicator.close();
        });
    },
    initPayBtn() {
      let pay_type = parseInt(window.localStorage.getItem("pay_type"));
      switch (pay_type) {
        case 1:
          this.payBtn.forEach((element, index) => {
            if (element.name == "积分支付") {
              this.payBtn.splice(index, 1);
            }
          });
          this.totalType = 1;
          this.payType = 1;
          break;
        case 2:
          this.payBtn.forEach((element, index) => {
            if (element.name == "微信支付") {
              this.payBtn.splice(index, 1);
            }
          });
          this.totalType = 2;
          this.payType = 3;
          break;
      }
    },
    fnSelectPayType(_num, _index) {
      this.payIndex = _index;
      this.payType = _num;
    },
    // 点击确实按钮
    paySubmit() {
      console.log(JSON.stringify(this.$route.params.list));
      let params = {
        goodsinfo: JSON.stringify(this.$route.params.list),
        pay_type: this.payType,
        site_id: this.$route.params.site_id,
        is_cart: this.$route.params.is_cart,
        standard: this.$route.params.standard,
        uid: this.$route.params.uid,
      };
      if(this.getlocalStorage('gettype')){
        params.goods_remark = this.getlocalStorage('gettype')
      }
      this.paramsObj = params;
      if (this.totalType == 2) {
        // 判断当前积分是否充足
        if (parseFloat(this.userscore) < parseFloat(this.total)) {
          Toast({
            message: "抱歉！你积分不足 请联系客服充值",
            duration: 2000
          });
          return;
        }
        this.showLayer = true;
      } else {
        Indicator.open({
          text: "支付中...",
          spinnerType: "fading-circle"
        });
        this.order_code ? this.getWxParams() : this.fnHandleOrder();
      }
    },

    // 生成订单函数
    fnHandleOrder() {
      console.log(this.paramsObj);
      console.log("参数");
      if (!this.isPayLoading) {
        this.isPayLoading = true;
        api
          .goodsbuypay(this.paramsObj)
          .catch(res => {
            //Indicator.close()
            console.warn(res);
            if (res.status == 200 && res.data.code === 0) {
              this.order_code = res.data.data.order_code;
              console.log(this.order_code);
              // 获取端微信支付参数
              this.totalType == 1 ? this.getWxParams() : this.integralPay();
            }
            if (res && res.data.code == 1) {
              Toast({
                message: res.data.msg,
                duration: 2000
              });
            }
            if(res && res.data.code == 2) {
              Toast(res.data.msg)
              setTimeout(() => {
                this.$router.push({
                  name: 'NewAudit'
                })
              }, 1500)
            }
          })
          .then(err => {
            Indicator.close();
          });
      }
    },

    /**
     * @author yang
     * @desc 使用积分支付
     * @param none
     */
    integralPay() {
      let params = {
        openid: this.ethelWxUserInfo.openid,
        password: this.payPsd,
        total_fee: this.$route.params.total,
        order_code: JSON.stringify(this.order_code)
      };
      let _this = this;
      api.getIntegralPay(params).catch(result => {
        Indicator.close();
        console.log(result);
        this.isPayLoading = true;
        if (result.status == 200) {
          Toast({
            message: result.data.msg,
            duration: 2000
          });
          if (result.data.code == 0) {
            let time = setTimeout(function() {
              clearTimeout(time);
              _this.$router.replace({
                path: "NewPayResult",
                query: {
                  result: true
                }
              });
            }, 2000);
          } else {
            let time = setTimeout(function() {
              clearTimeout(time);
              _this.$router.replace({
                path: "NewPayResult",
                query: {
                  result: false
                }
              });
            }, 2000);
          }
        }
      });
    },
    // 获取微信支付参数
    getWxParams() {
      let params = {
        openid: this.ethelWxUserInfo.openid,
        order_code: JSON.stringify(this.order_code),
        pay_type: "wx_goods",
        total_fee: this.$route.params.total
      };
      api
        .gzhwxpayparams(params)
        .catch(res => {
          if (res.status === 200 && res.data.code === 0) {
            //调起微信支付
            let result = res.data.data;
            console.log(result);
            let _this = this;
            this.wxChooseWXPay({
              appId: result.appid,
              timestamp: result.timeStamp,
              nonceStr: result.nonceStr,
              sign: result.sign,
              package: result.package,
              callback: function(msg = "") {
                Toast({
                  message: "支付成功",
                  duration: 2000
                });
                _this.isPayLoading = true;
                Indicator.close();
                let time = setTimeout(function() {
                  clearTimeout(time);
                  _this.$router.replace({
                    path: "NewPayResult",
                    query: {
                      result: true
                    }
                  });
                }, 2000);
              },
              errCallback: err => {
                // 支付失败 但是已经生成订单 需要跳转支付结果页面
                _this.isPayLoading = true;
                Toast({
                  message: "您已经取消支付",
                  duration: 2000
                });
                Indicator.close();
                // 调用取消支付接口
                _this.fnHandleWxCancel();
              }
            });
          }
        })
        .then(err => {
          Indicator.close();
        });
    },
    fnHandleWxCancel() {
      Indicator.open({
        text: "加载中...",
        spinnerType: "fading-circle"
      });
      let params = {
        uid: this.ethelWxUserInfo.id,
        order_code: JSON.stringify(this.order_code)
      };
      var _this = this;
      api
        .wxCancel(params)
        .catch(res => {
          Indicator.close();
          if (res.status == 200 && !res.data.code) {
            let time = setTimeout(function() {
              clearTimeout(time);
              _this.$router.replace({
                path: "NewPayResult",
                query: {
                  result: false
                }
              });
            }, 1000);
          }
        })
        .then(err => {
          Indicator.close();
        });
    }
  },
  components: {
    Scroll,
    ComHeader,
    Toast,
    Indicator
  }
};
</script>
